package com.zhen.controller;

import com.alibaba.fastjson.JSON;
import com.zhen.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    public void setGoodsService(GoodsService goodsService) {
        this.goodsService = goodsService;
    }


    @ResponseBody
    @RequestMapping(value = "/queryAllGoodsList")
    public String queryAllGoodsList(){
        return JSON.toJSONString(goodsService.queryAllGoods());
    }

    @ResponseBody
    @RequestMapping("/queryGoodsByName/{p1}")
    public String queryGoodsByName(@PathVariable String p1){
        return JSON.toJSONString(goodsService.queryGoodsByName(p1));
    }
    @RequestMapping("/addGoods")
    public String addGoods(@RequestParam("image") CommonsMultipartFile file,HttpServletRequest request) throws IOException {
        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String path = "D:\\work\\test04\\upload-images";
        File realPath = new File(path);
        if(!realPath.exists()){
            realPath.mkdir();
        }
        String realName = file.getOriginalFilename();
        String hou = realName.substring(realName.indexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String saveName = uuid+hou;
        //通过CommonsMultipartFile的方法直接写文件（注意文件路径和名称）
        file.transferTo(new File(realPath+"/"+saveName));
        goodsService.addGoods(name,Integer.parseInt(price),saveName);
        return "redirect:/index#/goodsManager";
    }

    @RequestMapping("/deleteGoodsById/{id}")
    public String deleteGoodsById(@PathVariable int id){
        goodsService.deleteGoodsById(id);
        return "redirect:/index#/goodsManager";
    }

}
